<template>
  <t-dialog
    :width="width ? width : '40%'"
    :visible="showDialog"
    @confirm="handleConfirm"
    @close="handleCancel"
    @cancel="handleCancel"
    :zIndex="zIndex || 2500"
    preventScrollThrough
    :placement="placement || 'center'"
  >
    <template #header>
      <t-space size="large">
        <div>{{ title || "选择内容" }}</div>
        <t-button size="small" v-if="showRefresh" @click="handleSelectTableRefresh">刷新列表</t-button>
      </t-space>
    </template>
    <slot name="toolkit" v-if="$slots.toolkit"></slot>
    <t-loading :loading="loading" text="正在载入...">
      <t-enhanced-table
        small="size"
        ref="selectTable"
        :row-key="rowKey || 'id'"
        activeRowType="single"
        :data="tableData"
        :columns="tableColumns"
        :filter-value="filterValue"
        table-layout="fixed"
        :tree="tableTreeOptions"
        :max-height="tableMaxHeight || '40vh'"
        :row-selection-type="rowSelectionType || 'single'"
        select-on-row-click
        :row-selection-allow-uncheck="true"
        @select-change="handleSelectChange"
        @filter-change="handleFilterChange"
        :scroll="scroll || { type: 'virtual' }"
        :pagination="
          pagination
            ? { ...pagination, pageSizeOptions: [5, 10, 20, 50, 100, 500, 1000, 2000, 5000, 10000] }
            : undefined
        "
        :defaultSelectedRowKeys="selectedRowKeys || []"
        @page-change="handlePageChange"
        bordered
        lazy-load
      />
    </t-loading>
  </t-dialog>
</template>

<script lang="tsx" setup>
import { computed, reactive } from "vue";
import dayjs from "dayjs";
import type { TableProps } from "tdesign-vue-next";

const props = defineProps([
  "mode",
  "title",
  "width",
  "loading",
  "showDialog",
  "rowKey",
  "treeOptions",
  "rowSelectionType",
  "tableData",
  "columns",
  "filterValue",
  "tableMaxHeight",
  "scroll",
  "pagination",
  "hideEditInfo",
  "zIndex",
  "showRefresh",
  "selectedRowKeys",
  "placement"
]);

const emits = defineEmits(["onCancel", "onConfirm", "currentChange", "filterChange", "pageChange", "onRefresh"]);

const tableColumns = computed(() => {
  const editInfoColumn: TableProps["columns"] = [
    {
      colKey: "createdTime",
      title: "创建时间",
      // sorter: true,
      width: 200,
      cell: (h, { row }) => {
        if (row.createdTime === null || row.createdTime === "") {
          return "没有记录";
        }
        return dayjs(row.createdTime).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    {
      colKey: "createdByName",
      title: "创建人",
      width: 200
    },
    {
      colKey: "updatedTime",
      title: "更新时间",
      width: 200,
      // sorter: true,
      cell: (h, { row }) => {
        if (row.updatedTime === null || row.updatedTime === "") {
          return "没有记录";
        }
        return dayjs(row.updatedTime).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    {
      colKey: "updatedByName",
      title: "更新人",
      width: 200
    }
  ];

  return [
    {
      colKey: "row-select",
      label: "选择",
      title: "选择",
      type: props.rowSelectionType,
      width: 60
    },
    ...props.columns,
    ...(props.hideEditInfo ? [] : editInfoColumn),
    {
      colKey: "remark",
      title: "备注",
      width: 450,
      ellipsis: {
        theme: "light",
        placement: "bottom"
      }
    }
  ] as TableProps["columns"];
});

const tableTreeOptions = computed(() => {
  if (props.mode === "tree") {
    if (props.treeOptions) {
      return props.treeOptions;
    } else {
      return { childrenKey: "children", treeNodeColumnIndex: 2 };
    }
  } else {
    return undefined;
  }
});

const selectedRow = reactive<Record<string, any>>({
  keys: [],
  options: {}
});

const handleSelectChange = (keys: Array<string | number>, options: Record<string, any>) => {
  selectedRow.keys = keys;
  selectedRow.options = options;
  const emitData = {
    keys,
    options
  };
  emits("currentChange", emitData);
};

const handleSelectTableRefresh = () => {
  emits("onRefresh");
};

const handleFilterChange = (filters: Record<string, any>, ctx: Record<string, any>) => {
  emits("filterChange", filters, ctx);
};

const handlePageChange = (pageInfo: Record<string, any>, newDataSource: Record<string, any>) => {
  emits("pageChange", pageInfo, newDataSource);
};
const handleCancel = () => {
  emits("onCancel");
};

const handleConfirm = () => {
  emits("onConfirm", selectedRow);
};
</script>
